﻿using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using SmallShop.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace SmallShop.Services.Implements
{
    public abstract class BaseMongoService<T> : IBaseMongoService<T> where T : class
    {
        protected static MongoDatabase db;
        protected BaseMongoService()
        {
            if (db == null)
            {
                var connectionString = ConfigurationManager.AppSettings["mongourl"];
                var client = new MongoClient(connectionString);
                db = client.GetServer().GetDatabase(ConfigurationManager.AppSettings["mongodatabase"]);
            }
        }
        protected abstract MongoCollection<T> GetCollection();

        public virtual void Add(T Entity)
        {
            GetCollection().Insert<T>(Entity);
        }

        public virtual void Update(T Entity)
        {
            GetCollection().Save<T>(Entity);
        }


        public virtual T GetById(string Id)
        {
            var query = Query.EQ("_id", new ObjectId(Id));
            return GetCollection().FindOne(query);
        }

        public virtual IEnumerable<T> All()
        {
            return GetCollection().FindAllAs<T>();
        }
    }
}
